//
//  LoginViewController
//  RxT
//
//  Created by LiChendi on 16/3/4.
//  Copyright © 2016年 LiChendi. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift

let minUsernameLength = 5
let maxUsernameLength = 10
let minPasswordLength = 5
let maxPasswordLength = 16
let disposeBag = DisposeBag()

class LoginViewController: UIViewController {
  
    @IBOutlet weak var usernameTF: UITextField!
    @IBOutlet weak var usernameLB: UILabel!
    @IBOutlet weak var passwordTF: UITextField!
    @IBOutlet weak var passwordLB: UILabel!
    @IBOutlet weak var loginButton: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()

    
        let usernameValid = usernameTF.rx.text
            .map{($0?.count)! >= minUsernameLength && ($0?.count)! <= maxUsernameLength }  //map函数 对text进行处理
            .share(replay: 1)     //
        
        let passwordValid = passwordTF.rx.text
            .map{($0?.count)! >= minPasswordLength && ($0?.count)! < maxPasswordLength }  //map函数 对text进行处理
            .share(replay: 1)     //
        
        
        let everythingValid = Observable.combineLatest(usernameValid, passwordValid) { $0 && $1 }
            .share(replay: 1)
        
        _ = usernameValid.bind(to: passwordTF.rx.isEnabled)
//        _ = usernameValid.bind(to: usernameLB.rx.isHidden) //username通过验证，usernameLB警告消失
        let observer: Binder<Bool> = Binder(usernameLB) {
            $0.isHidden = $1
        }
        
        usernameValid.bind(to: observer).disposed(by: disposeBag)
        _ = passwordValid.bind(to: passwordLB.rx.isHidden)
        _ = everythingValid.bind(to: loginButton.rx.isEnabled)  // 用户名密码都通过验证，才可以点击按钮
        _ = loginButton.rx.tap.subscribe(onNext: {
            [weak self] in
            self?.showAlert()
         })
        

    }


//    private func throttle() {
//        let result = usernameLB.rx.text.throttle(0.3, MainScheduler.instance).
//    }
    
    
    func showAlert() {
        let alertController = UIAlertController(title: "成功", message: "登录成功", preferredStyle: .alert)
        let action = UIAlertAction(title: "alertAction", style: .default) { (action) in
            
        }
        alertController.addAction(action)
        present(alertController, animated: true) {
        }
 
    }
}
